package dream.web;

import dream.pojo.AppVar;
import dream.pojo.User;
import dream.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


@WebServlet("/automaticLogin")
public class AutomaticLoginServlet extends HttpServlet {
    private UserService userService = new UserService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //实现自动加密
        //获取id以及加密后的ids，从新使用MD5加密求出ids1，判断id是否被篡改
        String id = null;
        String ids = null;
        String ids1 = null;
        Cookie[] cookies = req.getCookies();

        if(cookies == null){
            return;
        }

        for(Cookie c :cookies ){
            if(c.getName().equals("id")){
                id = c.getValue();
                continue;
            }
            if(c.getName().equals("ids")){
                ids = c.getValue();
                continue;
            }
        }

        if(ids == null){
            return;
        }

        try {
            MessageDigest digest = MessageDigest.getInstance("md5");
            digest.update(("nothing" + id).getBytes());
            ids1 = new BigInteger(1, digest.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        if(ids1.equals(ids)){
            User user = userService.SelectById(Integer.valueOf(id));

            //将当前登录的用户保存到session中
            //得到session对象
            HttpSession session1 = req.getSession(true);
            if(session1 != null){
                session1.setAttribute(AppVar.SESSION_USERINFO_KEY, user);
            }
            resp.getWriter().println("1");
        }else {
            return;
        }
    }
}
